package com.yeshine.opendata.controller;

import com.yeshine.opendata.controller.front.AbstractFrontControllerBase;
import com.yeshine.opendata.entity.*;
import com.yeshine.opendata.service.*;
import com.yeshine.opendata.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by taohj on 2014/7/7.
 */
@Controller
public class CommonController extends AbstractFrontControllerBase {


    @Autowired
    private IDataService dataService;

    @Autowired
    private IDataThemeService dataThemeService;

    @Autowired
    private IAppThemeService appThemeService;

    @Autowired
    private IOrgService orgService;


    @Autowired
    private IDataSetService dataSetService;


    @Autowired
    private IDictionaryService dictionaryService;

    @RequestMapping("404")
    public String _404() {
        return "404";
    }

    @RequestMapping({"", "index", "/"})
    public String index() {


        PageResult<Data> dataPageResult = new PageResult<Data>();
        dataPageResult.setT(new Data());
        dataPageResult.setPage(1);
        dataPageResult.setSize(10);
        dataPageResult.setSortColumn("data.CreateTime");
        dataPageResult.setSortBy("desc");
        List<Data> topDatas = dataService.getByPage(dataPageResult).getPageResult().getRows();
        setRequestAttr("topDatas", topDatas);


        setRequestAttr("orgs", orgService.getList(null).getList());
        setRequestAttr("themes", dataThemeService.getList(null).getList());
        setRequestAttr("tags", dataService.getTopTags(null));
        return super.getPagePath("index");
    }


    @ResponseBody
    @RequestMapping("getDictionarys")
    public String getDictionary(
            @RequestParam("type") String type
    ) {
        return dictionaryService.getList(new SysDictionary(type)).toString();
    }

    @ResponseBody
    @RequestMapping("getDataThemes")
    public String getDataTheme() {
        return dataThemeService.getList(null).toString();
    }

    @ResponseBody
    @RequestMapping("getAPPThemes")
    public String getAPPTheme() {
        return appThemeService.getList(null).toString();
    }


    @ResponseBody
    @RequestMapping("getOrgs")
    public String getOrgs(
            @RequestParam(value = "creater", required = false) Integer creater
    ) {
        Org org = new Org();
        org.setCreater(getCurrentUser());
        return orgService.getList(org).toString();
    }


    @ResponseBody
    @RequestMapping("getDatasets")
    public String getOrgs(
            @RequestParam(value = "org", required = false) Integer org,
            @RequestParam(value = "creater", required = false) Integer creater
    ) {
        DataSet dataSet = new DataSet();
        dataSet.setOrg(new Org(org));
        dataSet.setCreater(new User(creater));
        return dataSetService.getList(dataSet).toString();
    }

  @RequestMapping("dataFiledownload")
    public void dataFiledownload(
            HttpServletResponse response,
            @RequestParam("id") Integer id
    ) throws UnsupportedEncodingException {
        Data data = dataService.getById(id).getTarget();


        String realpath = getRequest().getSession().getServletContext().getRealPath(data.getUrl());

        // String realpath="C:/Users/taohj/Desktop/根据时间段获得每一年或者每一月 或者每一天.txt";
         String str=realpath;
         String filename = str.substring(str.lastIndexOf("/")+1); // 文件名，输出到用户的下载对话框
      if (filename.indexOf("\\")>0){
          filename = filename.substring(filename.lastIndexOf("\\")+1);
      }
         filename=new String(filename.getBytes(),"8859_1");
      // 打开指定文件的流信息
        java.io.FileInputStream fs = null;
        try {
            fs = new java.io.FileInputStream(new java.io.File(realpath));
        } catch (java.io.FileNotFoundException e) {
            e.printStackTrace();
        }
        // 设置响应头和保存文件名

        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + filename + "\"");
        // 写出流信息
        int b = 0;
        try {
            java.io.PrintWriter out = response.getWriter();
            while ((b = fs.read()) != -1) {
                out.write(b);
            }
            fs.close();
            out.close();
            System.out.println("文件下载完毕.");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("下载文件失败!");
        }
    }


    public  static void main(String [] args){
        String str="/upload/data/data/7795/技术建议书-炎翔.doc";
        System.out.println(str.substring(str.lastIndexOf("/")+1));
    }




   /* @RequestMapping("wordtest")
    public  void wordTest(HttpServletResponse response) throws IOException {
        String url="http://localhost:80/upload/3.doc";
        OfficeExtractor extractor=new OfficeExtractor();
        extractor.wordExtractor(response,url);
    }
*/





}
